package handle

import (
	"fileServer/cfile"
	"fileServer/global"
	"fileServer/setting"
	"github.com/gin-gonic/gin"
	"io"
	"io/ioutil"
	"log"
	"os"
	"runtime"
)

func showFileList(path, reqPath string, c *gin.Context) {
	var files []cfile.InfoString
	var file_ cfile.InfoString
	fileInfoList, err := ioutil.ReadDir(path)
	if err != nil {
		log.Println(err)
		return
	}
	for i := range fileInfoList {
		file_.FileInfoToString(i+1, reqPath, fileInfoList[i])
		sysType := runtime.GOOS
		if sysType == "windows" {
			// windows系统
			if !cfile.CheckIsHidden(fileInfoList[i]) {
				files = append(files, file_)
			}
		} else {
			files = append(files, file_)
		}

	}
	global.GetResult(c).TempleSuccess(gin.H{
		"files":          files,
		"path":           setting.Setting.PrefixURL + reqPath,
		"rootPath":       setting.Setting.PrefixURL,
		"uploadFilePath": setting.Setting.UploadPath,
		"deleteFilePath": setting.Setting.DeletePath,
		"mkdirPath":      setting.Setting.MkdirPath,
		"getMdePath":     setting.Setting.MD5Path,
	})
}
func getFile(filePath string, c *gin.Context) {
	file, err := os.Open(filePath)
	if err != nil {
		global.GetResult(c).TempleError(400103, "打开文件错误")
		return
	}
	defer file.Close() // 延迟操作， file close
	c.Writer.Header().Add("Content-type", "application/octet-stream")
	_, err = io.Copy(c.Writer, file)
	if err != nil {
		global.GetResult(c).TempleError(400102, "读取文件失败")
		return
	}
}
func FileListInfo(c *gin.Context) {
	reqPath := c.Param(setting.Setting.URLKey)    // 获取请求的路由参数
	fullPath := setting.Setting.DIRPath + reqPath // 目录起始路径 + 请求地址 组合成完整的路径
	fileInfo, err := os.Stat(fullPath)
	if err != nil {
		log.Println("show path for", fullPath, err.Error())
		global.GetResult(c).TempleError(400101, "获取文件信息错误")
		return
	}
	if fileInfo.IsDir() {
		showFileList(fullPath, reqPath, c)
		return
	}
	getFile(fullPath, c)
}

func GetMD5(c *gin.Context) {
	if setting.MD5Running.State == 1 {
		global.GetResult(c).Error(400900, "接口正在计算中", "重复调用接口")
		return
	}
	setting.MD5Running.State = 1
	filePath, _ := GetFilePath(c)
	md5, err := cfile.CalcFileMD5(filePath)
	if err != nil {
		global.GetResult(c).TempleError(400105, "获取文件MD5信息错误")
		return
	}
	setting.MD5Running.State = 0
	global.GetResult(c).Success(gin.H{"md5": md5})
}
